package com.yly.plugindemo;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;

import dalvik.system.DexClassLoader;

/**
 * 文件名: AssetUtils.java
 * 描述:
 * 修改人: [zhengge]
 * 修改日期: 2018-12-07
 * 修改内容: 新增
 */
public class AssetUtils {
	public static AssetManager sAssetManager;
	public static Resources sResources;
	public static HashMap<String,PluginInfo> pluginInfos = new HashMap<>();

	public static void addAssetPath(Context context,String apkName){
		try {
			AssetManager assetManager = AssetManager.class.newInstance();
			Method addAssetPath = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
			addAssetPath.invoke(assetManager,pluginInfos.get(apkName).getDexPath());
			sResources = new Resources(assetManager,
					context.getResources().getDisplayMetrics(),
					context.getResources().getConfiguration());
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * @param context baseContext
	 * @param apkName 文件路径
	 */
	public static void extractInfo(Context context,String apkName){
		File apkPath = context.getFileStreamPath(apkName);
		DexClassLoader dexClassLoader = new DexClassLoader(
				apkPath.getAbsolutePath(),
				context.getDir("dex", Context.MODE_PRIVATE).getAbsolutePath(),
				null,
				context.getClassLoader());//Parent is BaseDexClassLoader 还是 PathClassLoader
		PluginInfo pluginInfo = new PluginInfo(apkPath.getAbsolutePath(), dexClassLoader);
		pluginInfos.put(apkName, pluginInfo);
	}
}
